////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.more;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import cc.telecomdigital.tdstock.BaseAsyncTask;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.DBHelper;
import cc.telecomdigital.tdstock.DefaultClickHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.LightStreamerHandlerInterface;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.StringUtils;
import cc.telecomdigital.tdstock.CommonDefn.DataMode;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.LS_SubscriptionItem;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Response;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.BaseActivity;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.MonitorUtil;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.SaveBookMarkAsyncTask;
import cc.telecomdigital.tdstock.model.GoldFuturesInfo;
import cc.telecomdigital.tdstock.model.IntlMetalInfo;

import com.lightstreamer.ls_client.UpdateInfo;

/**
 * 
 * @author haibo
 * 
 *         for menu item caption is "metal"
 * 
 */
public class MetalActivity extends BaseActivity implements
	LightStreamerHandlerInterface, ILS_UserClient_Response
{
	public final String				TAG						= MetalActivity.class
																.getSimpleName();
	private Button					_toolBtnReturn;
	private TextView[][]			_goldFuturestv				= new TextView[2][7];
	private int[][]				_goldFutures_tv_ids			= {
			{ R.id.gold_futures_hk_mm1, R.id.gold_futures_hk_price1,
			R.id.gold_futures_hk_net1, R.id.gold_futures_hk_vol1,
			R.id.gold_futures_hk_high1, R.id.gold_futures_hk_low1,
			R.id.gold_futures_hk_open1 },
			{ R.id.gold_futures_hk_mm2, R.id.gold_futures_hk_price2,
			R.id.gold_futures_hk_net2, R.id.gold_futures_hk_vol2,
			R.id.gold_futures_hk_high2, R.id.gold_futures_hk_low2,
			R.id.gold_futures_hk_open2 }						};
	private final static String[]		SUBSCRIBE_GOLD_FUTURES_ITEMS	= {
			"GLD:1", "GLD:2"								};						// attention, depend the order of the elements;
	private final static String[]		SUBSCRIBE_GOLD_FUTURES_FIELDS	= {
			GoldFuturesInfo.METALMM, GoldFuturesInfo.METALLAST,
			GoldFuturesInfo.METALNET, GoldFuturesInfo.METALVOL,
			GoldFuturesInfo.METALHIGH, GoldFuturesInfo.METALLOW,
			GoldFuturesInfo.METALOPEN						};						// attention, depend the order of the
																				// elements;

	private final static String[]		SUBSCRIBE_INTL_META_ITEMS	= {
			"XAU", "GCV9", "HKGG", "XAG", "COPPER", "NICKEL", "ALUM", "ZINC" };				// attention,
																				// depend
																				// the order
																				// of the
																				// elements;
	private final static String[]		SUBSCRIBE_INTL_META_FIELDS	= {
			IntlMetalInfo.METALNAME, IntlMetalInfo.METALHIGH,
			IntlMetalInfo.METALLOW, IntlMetalInfo.METALLAST,
			IntlMetalInfo.METALNET, IntlMetalInfo.METALBID,
			IntlMetalInfo.METALASK							};

	private TextView[][]			_intlMetal				= new TextView[4][2];
	private final static int[][]		_intlMetal_tv_ids			= {
			{ R.id.metal_cu_price, R.id.metal_cu_net },
			{ R.id.metal_ni_price, R.id.metal_ni_net },
			{ R.id.metal_al_price, R.id.metal_al_net },
			{ R.id.metal_zi_price, R.id.metal_zi_net },			};

	private final static int[]		SUBSCRIBE_OTHERS_LABEL_IDS	= {
			R.string.more_metal_item_label_london,
			R.string.more_metal_item_label_goldfutures,
			R.string.more_metal_item_label_hkgold,
			R.string.more_metal_item_label_silver				};

	private final static int[]		SUBSCRIBE_OTHERS_HOLDER_IDS	= {
			R.id.metal_gold_london, R.id.metal_gold_futures,
			R.id.metal_gold_hk, R.id.metal_silver_london		};

	private final String			TAG_NAME					= "fx_name";
	private final String			TAG_MONITOR				= "addto_monitor_tag";
	private final String[]			TAGS						= {
			"fx_buy", "fx_sell", "fx_high", "fx_low"			};
	private TextView[][]			_others_tv_holder			= new TextView[4][4];
	private boolean				_isSubscribed				= false;
	// private static StreamerTimeoutHandler _streamerTimeoutHandler;

	private static String			IDENTIFIER_0				= MetalActivity.class
																.getSimpleName()
																+ "00";
	private static String			IDENTIFIER_1				= MetalActivity.class
																.getSimpleName()
																+ "01";

	private CallBackHandlerOnIntlMetal	_callBackHandlerOnIntlMetal;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.metal);

		/*
		 * _streamerTimeoutHandler = new StreamerTimeoutHandler(this,
		 * _messageHandler);
		 */
		resetMinHeightOnWorkCenter();
		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG,
						"close current activity and forwarding to the previous");
				String cameFrom = ((ITDLApplication) getApplicationContext())
						.getString(CommonDefn.ACTIVITY_CAME_FROM_KEY);

				((ITDLApplication) getApplicationContext()).putString(
						CommonDefn.ACTIVITY_CAME_FROM_KEY, "");

				Intent intent = new Intent(getApplicationContext(),
						MoreActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(MoreActivity.class, intent);

			}

		});

		if (((ITDLApplication) getApplicationContext()).getDataMode() == DataMode.Delay)
		{
			((TextView) findViewById(R.id.metal_title))
					.setText(getResources().getString(R.string.more_metal)
							+ "("
							+ getResources().getString(
									R.string.delay_mode_title_tips)
							+ ")");
		}

		initViews();

	}

	@Override
	protected void onPause()
	{
		super.onPause();
	}

	@Override
	protected void onRestart()
	{
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();
		/* connectLightStreamer(); */

		/*
		 * if (_streamerTimeoutHandler != null) {
		 * _streamerTimeoutHandler.startCounter(0,0); }
		 */
		/*
		 * if (!_isSubscribed) {
		 */
		/* onConnectionEstablished(); */
		/*
		 * final Runnable myUpdateResults = new Runnable() { public void run() {
		 * onConnectionEstablished(); } };
		 * 
		 * new Thread() { public void run() {
		 * _messageHandler.post(myUpdateResults); } }.start();
		 */
		/*
		 * new SubscriptionTask(MetalActivity.this.getMyOwnContext())
		 * .execute();
		 */

		/* } */
	}

	public void onUpdate(final int itemPos, final String itemName,
			final UpdateInfo update)
	{
		final Runnable myUpdateResults = new Runnable()
		{
			public void run()
			{
				TextView[] holder = _goldFuturestv[itemPos - 1];
				for (int index = 0, indexLength = holder.length; index < indexLength; index++)
				{
					Object fieldOriginalValue = update
							.getNewValue(SUBSCRIBE_GOLD_FUTURES_FIELDS[index]);
					String fieldValue = fieldOriginalValue == null ? CommonDefn.DEFAULT_FIELD_VALUE
							: update.getNewValue(SUBSCRIBE_GOLD_FUTURES_FIELDS[index]);
					if (index == 2)
					{
						holder[index].setTextColor(fieldValue
								.indexOf("-") >= 0 ? Color.RED
								: Color.GREEN);
						holder[index].setText(StringUtils.formatString(
								fieldValue,
								fieldValue.indexOf("-") >= 0 ? null
										: "+", null));
						holder[index].setTypeface(Typeface.MONOSPACE);
					}
					else
					{
						holder[index].setText(fieldValue);
					}
					// holder[index].postInvalidate();
				}
			}
		};

		new Thread()
		{
			public void run()
			{
				if (_messageHandler != null)
					_messageHandler.post(myUpdateResults);
			}
		}.start();
	}

	private void initViews()
	{
		// -----init Gold Futures--------
		for (int line = 0, lineCount = _goldFuturestv.length; line < lineCount; line++)
		{
			for (int col = 0, colCount = _goldFuturestv[0].length; col < colCount; col++)
			{
				_goldFuturestv[line][col] = (TextView) findViewById(_goldFutures_tv_ids[line][col]);
			}
		}
		// -----init Gold Futures--------

		// -----init INTL META----------
		for (int line = 0, lineCount = _intlMetal.length; line < lineCount; line++)
		{
			for (int col = 0, colCount = _intlMetal[0].length; col < colCount; col++)
			{
				_intlMetal[line][col] = (TextView) findViewById(_intlMetal_tv_ids[line][col]);
			}
		}
		// -----init INTL META----------

		// --init others item
		for (int line = 0, lineCount = _others_tv_holder.length; line < lineCount; line++)
		{
			ViewGroup currentContainer = (ViewGroup) findViewById(SUBSCRIBE_OTHERS_HOLDER_IDS[line]);

			((TextView) currentContainer.findViewWithTag(TAG_NAME))
					.setText(SUBSCRIBE_OTHERS_LABEL_IDS[line]);
			TextView[] holder = _others_tv_holder[line];
			for (int item = 0, itemCount = holder.length; item < itemCount; item++)
			{
				// each index has a tag
				holder[item] = (TextView) currentContainer
						.findViewWithTag(TAGS[item]);
			}
			if (line == lineCount - 1)
			{
				((Button) currentContainer.findViewWithTag(TAG_MONITOR))
						.setVisibility(View.INVISIBLE); // don't allow to add
													// this item to monitor;
			}
			else
			{
				// set the button's click action
				Button addToMonitor = ((Button) currentContainer
						.findViewWithTag(TAG_MONITOR));
				addToMonitor
						.setOnClickListener(new AddGoldInfoClickHandler(
								MetalActivity.this,
								SUBSCRIBE_INTL_META_ITEMS[line],
								getResources()
										.getString(
												SUBSCRIBE_OTHERS_LABEL_IDS[line])));
			}

		}

		// --init others item

	}

	private void subscriteMetalInfo()
	{
		try
		{

			/*
			 * _myClient = ((ITDLApplication) getApplicationContext())
			 * .getLightStreamerClient();
			 * 
			 * subscribeMultiple(_myClient, SUBSCRIBE_GOLD_FUTURES_ITEMS,
			 * SUBSCRIBE_GOLD_FUTURES_FIELDS, GoldFuturesInfo.ADAPTER, this);
			 */

			List<String> iIdList = new ArrayList<String>();
			List<LS_SubscriptionItem> iItemList = new ArrayList<LS_SubscriptionItem>();
			List<ILS_UserClient_Response> iResponseList = new ArrayList<ILS_UserClient_Response>();

			LS_SubscriptionItem interestItem = new LS_SubscriptionItem(
					GoldFuturesInfo.ADAPTER);
			for (String item : SUBSCRIBE_GOLD_FUTURES_ITEMS)
				interestItem.AddSubscribeItem(item);
			for (String field : SUBSCRIBE_GOLD_FUTURES_FIELDS)
				interestItem.AddSubscribeSchema(field);

			/*
			 * IDENTIFIER_0 = LSGetUniqueID(); if
			 * (LightStreamerSubscribeItem(IDENTIFIER_0, interestItem,this)) {
			 * 
			 * }
			 * 
			 * 
			 * try { Thread.sleep(500); } catch (InterruptedException e) { //
			 * TODO Auto-generated catch block e.printStackTrace(); }
			 */

			iIdList.add(IDENTIFIER_0);
			iItemList.add(interestItem);
			iResponseList.add(this);
			/*
			 * subscribeMultiple(_myClient, SUBSCRIBE_INTL_META_ITEMS,
			 * SUBSCRIBE_INTL_META_FIELDS, IntlMetalInfo.ADAPTER, new
			 * CallBackHandlerOnIntlMetal());
			 */

			if (_callBackHandlerOnIntlMetal == null)
			{
				_callBackHandlerOnIntlMetal = new CallBackHandlerOnIntlMetal();
			}

			LS_SubscriptionItem metaItems = new LS_SubscriptionItem(
					IntlMetalInfo.ADAPTER);
			for (String item : SUBSCRIBE_INTL_META_ITEMS)
				metaItems.AddSubscribeItem(item);
			for (String field : SUBSCRIBE_INTL_META_FIELDS)
				metaItems.AddSubscribeSchema(field);

			/*
			 * IDENTIFIER_1 = LSGetUniqueID(); if
			 * (LightStreamerSubscribeItem(IDENTIFIER_1, metaItems,this)) {
			 * 
			 * }
			 */

			iIdList.add(IDENTIFIER_1);
			iItemList.add(metaItems);
			iResponseList.add(this);

			LightStreamerSubscribeItemsInBatch(iIdList, iItemList,
					iResponseList);

			TDStockLog.d(TAG, "add  Items!");
		}

		catch (Exception e)
		{
			TDStockLog.d(TAG, "other exception!" + e.getMessage());
		}
	}

	private class CallBackHandlerOnIntlMetal implements
		LightStreamerHandlerInterface
	{

		@Override
		public synchronized void onUpdate(final int itemPos,
				final String itemName, final UpdateInfo update)
		{
			final Runnable myUpdateResults = new Runnable()
			{
				public void run()
				{
					try
					{
						String last = update
								.getNewValue(IntlMetalInfo.METALLAST);
						String net = update
								.getNewValue(IntlMetalInfo.METALNET);
						String high = update
								.getNewValue(IntlMetalInfo.METALHIGH);
						String low = update
								.getNewValue(IntlMetalInfo.METALLOW);
						String bid = update
								.getNewValue(IntlMetalInfo.METALBID);
						String ask = update
								.getNewValue(IntlMetalInfo.METALASK);
						if (itemPos >= 5 && itemPos <= 8)
						{
							_intlMetal[itemPos - 5][0]
									.setText(last == null ? CommonDefn.DEFAULT_FIELD_VALUE
											: last);
							if (net != null)
							{
								_intlMetal[itemPos - 5][1]
										.setTextColor(net
												.indexOf("-") >= 0 ? Color.RED
												: Color.GREEN);
								_intlMetal[itemPos - 5][1]
										.setText(StringUtils
												.formatString(
														net,
														net.indexOf("-") >= 0 ? null
																: "+",
														null));
								_intlMetal[itemPos - 5][1]
										.setTypeface(Typeface.MONOSPACE);
							}
							else
							{
								_intlMetal[itemPos - 5][1]
										.setText(CommonDefn.DEFAULT_FIELD_VALUE);
							}
							_intlMetal[itemPos - 5][0].postInvalidate();
							_intlMetal[itemPos - 5][1].postInvalidate();
						}
						else
						{
							// it's the others;
							TextView[] holder = _others_tv_holder[itemPos - 1];
							String[] values = { bid, ask, high, low };
							for (int index = 0; index < 4; index++)
							{
								holder[index].setText(values[index]);
							}
							for (int index = 0; index < 4; index++)
								holder[index].postInvalidate();

						}
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}

				}
			};

			new Thread()
			{
				public void run()
				{
					if (_messageHandler != null)
						_messageHandler.post(myUpdateResults);
				}
			}.start();

		}
	}

	public void onConnectionEstablished()
	{
		/*
		 * try { Thread.sleep(500); } catch (InterruptedException e) { // TODO
		 * Auto-generated catch block e.printStackTrace(); }
		 */
		subscriteMetalInfo();
	}

	private class AddGoldInfoClickHandler extends DefaultClickHandler
	{
		private String	_item;
		private String	_itemName;

		public AddGoldInfoClickHandler(Context context, String item,
				String itemName)
		{
			super(context);
			_item = item;
			_itemName = itemName;
		}

		@Override
		protected void onDefaultAction()
		{
			// 延迟模式
			if (((ITDLApplication) getApplicationContext()).getModeType() == CommonDefn.ModeType.DELARY)
			{
				DBHelper dbHelper = new DBHelper(MetalActivity.this);
				try
				{
					int customerId = 1;

					if (dbHelper.isSubscribeItemExist(customerId, _item,
							IntlMetalInfo.ADAPTER))
					{
						new CustomizeDialog(getMyOwnContext(), "",
								getResources().getString(
										R.string.monitor_exist_index))
								.show();
						/*
						 * new AlertDialog.Builder(
						 * MetalActivity.thisgetMyOwnContext()) .setTitle(
						 * getResources().getString( R.string.info))
						 * .setMessage( getResources() .getString(
						 * R.string.monitor_exist_index)) .setIcon(
						 * getResources() .getDrawable(
						 * R.drawable.help_menu_icon)) .setPositiveButton(
						 * getResources().getString( R.string.ok), new
						 * DialogInterface.OnClickListener() { public void
						 * onClick( DialogInterface dialoginterface, int i) {
						 * 
						 * } }).show();
						 */
					}
					else if (dbHelper.isFullWithItemInMonitor(customerId))
					{
						new CustomizeDialog(
								getMyOwnContext(),
								"",
								getResources()
										.getString(
												R.string.monitor_is_full_with_items))
								.show();
						/*
						 * new AlertDialog.Builder(
						 * ForeignExchangeActivity.thisgetMyOwnContext())
						 * .setTitle( getResources().getString( R.string.info))
						 * .setMessage( getResources() .getString(
						 * R.string.monitor_is_full_with_items)) .setIcon(
						 * getResources() .getDrawable(
						 * R.drawable.help_menu_icon)) .setPositiveButton(
						 * getResources().getString( R.string.ok), new
						 * DialogInterface.OnClickListener() { public void
						 * onClick( DialogInterface dialoginterface, int i) { }
						 * }).show();
						 */
					}
					else
					{
						long result = dbHelper.insertSubscribeItem(
								customerId, _item,
								IntlMetalInfo.ADAPTER, _itemName,
								IntlMetalInfo.METALASK,
								CommonDefn.DEFAULT_FIELD_VALUE,
								CommonDefn.DEFAULT_FIELD_VALUE);
						if (result > 0)
						{
							/* modify by zor(ouyangzhihui) */
							String temp = _item.length() >= 2 ? _item
									.substring(0, 2) : _item;
							startAnimat(temp);
						}

						TDStockLog.d(TAG, "insert result:" + result);
						TDStockLog.d(TAG, "insert result:" + result);
					}

				}
				catch (NotFoundException e)
				{
					e.printStackTrace();
					TDStockLog.d(
							TAG,
							"insert result:" + e.getMessage() == null ? "unknown exception!"
									: e.getMessage());
				}
				finally
				{
					dbHelper.cleanup();
				}
			}
			// 非延迟模式
			else
			{
				new SaveBookMarkAsyncTask(_item,
						CommonDefn.BookMarkType.metal.getBookMarkType(),
						MetalActivity.this, MonitorUtil.getInstance(),
						_item.length() >= 2 ? _item.substring(0, 2)
								: _item).execute();
			}
		}

	}

	private class SubscriptionTask extends BaseAsyncTask
	{

		public SubscriptionTask(Context context)
		{
			super(context);
		}

		@Override
		protected Void doInBackground(String... params)
		{
			onConnectionEstablished();
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
		}
	}

	protected Context getMyOwnContext()
	{
		// return _context;
		return getParent();
	}

	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return MoreGroup.GetActivityGroupHostControl();
	}

	@Override
	public void onUpdate(String iIdentifier, int iSchemaIndex,
			String iSchemaValue, UpdateInfo iUpdateInfo)
	{

		super.onUpdate(iIdentifier, iSchemaIndex, iSchemaValue, iUpdateInfo);
		if (IDENTIFIER_1.equals(iIdentifier))
		{
			_callBackHandlerOnIntlMetal.onUpdate(iSchemaIndex, iSchemaValue,
					iUpdateInfo);
		}
		else if (IDENTIFIER_0.equals(iIdentifier))
		{
			this.onUpdate(iSchemaIndex, iSchemaValue, iUpdateInfo);
		}

	}

}
